#ifndef _DEF_H_
#define _DEF_H_

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/times.h>
#include <fcntl.h>
#include <errno.h>
#include <stdint.h>
#include <assert.h>

#ifdef __cplusplus
extern "C"{
#endif

typedef void *(*thread_func) (void *self);

#define RET_SUCCESS 0


#ifdef DEBUG
#define p_debug printf

#define DBG(fmt, args...) do{\
    printf("[%s():%d] " fmt "\n", __FUNCTION__, __LINE__, ##args);\
    }while(0)

#define FDBG(f, fmt, args...) do{\
    fprintf(f, "[%s():%d] " fmt "\n", __FUNCTION__, __LINE__, ##args);\
    }while(0)

#else
#define p_debug(...)
#define DBG(fmt, args...) 
#define FDBG(f, fmt, args...) 
#endif

#define ERR(fmt, args...) do{\
    printf("[%s():%d] " fmt "\n", __FUNCTION__, __LINE__, ##args);\
    perror("");\
    }while(0)

#define ENTER() DBG("Enter")
#define EXIT()  DBG("Exit");


#define MALLOC(n) calloc(1, (n))

#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif

#ifndef MAX
#define MAX(a, b) (((a) >= (b)) ? (a) : (b))
#endif

#ifndef BIT
#define BIT(val, i) ((val) & (0x1 << (i)))
#endif

#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#define FIELD_SIZEOF(t, f) (sizeof(((t *)0)->f))

#define ENTER_FUNC() do{\
    p_debug("\nEnter %s()\n", __FUNCTION__);\
    }while(0)

#define EXIT_FUNC() do{\
    p_debug("Exit %s()\n", __FUNCTION__);\
    }while(0)

#define safe_free(p) do{\
    if((p) != NULL)\
    {\
        free((p));\
        (p) = NULL;\
    }\
    }while(0)

#define safe_fclose(f) do{\
    if((f) != NULL)\
    {\
        fclose((f));\
        (f) = NULL;\
    }\
    }while(0)

#define safe_close(fd) do{\
    if((fd) > 0)\
    {\
        close((fd));\
        (fd) = -1;\
    }\
    }while(0)

#define MEMSET(o) memset(&(o), 0, sizeof(o))
#define MEMSET_P(p) memset(p, 0, sizeof(*(p)))


#ifdef __cplusplus
}
#endif

#endif
